<?php
// $Id: CarClassModule.php 592 2012-12-12 07:43:28Z tomqin@gmail.com $

/**
 * Part of the framework.
 *
 * @package     Module
 * @version     1.0
 * @copyright   Copyright (C) 2010-2012 SupeFun.com Inc.
 * @author      TomQin <tomqin@gmail.com>
 * @license     http://www.supefun.com/license/
 */

class CarClassModule{
    public $data = array();
    public $maps = array();

    public function __construct(){

    }

    public function getData(){
        $result = Db::query("SELECT ccid,pid,level,title FROM `db_foolcars`.`cms_coclass` WHERE coid=1 ORDER BY vieworder", 'ccid');
        while($row = $result->fetch_assoc()){
            $this->data[$row['ccid']]  = $row;
            $this->maps[$row['pid']][] = $row['ccid'];
        }
        return $this;
    }

    public function getJSONList($pid){
        $arr = array();
        $pid = intval($pid);
        if(isset($this->maps[$pid])){
            foreach($this->maps[$pid] as $id){
                if(isset($this->data[$id])){
                    $arr[] = array(
                        'id'   => $this->data[$id]['ccid'],
                        'text' => isset($this->maps[$id]) ? $this->data[$id]['title'] : '<A href="/?">'.$this->data[$id]['title'].'</A>',
                        'classes' => isset($this->maps[$id]) ? 'folder' : 'file',
                        'hasChildren' => (bool)isset($this->maps[$id]),
                    );
                }
            }
        }
        return json_encode($arr);
    }

    public function showTree($id, $maps = array()){
        if(empty($maps) || !is_array($maps)){
            $maps = $this->maps[0];
        }
        echo '<ul class="cartree treeview" id="'.$id.'">';
        foreach($maps as $id){
            echo $this->recursiveTreeItem($id);
        }
        echo '</ul>';
    }

    public function recursiveTreeItem($carid){
        $string = '';
        if(isset($this->data[$carid])){
            $item    = $this->data[$carid];
            $class   =(is_array($this->maps[$carid]) || $item['level'] <2) ? 'folder' : 'file';

            if($item['level'] == 2){
                $template = '<li><a href="#%1$d"><span id="car-%1$d" class="%2$s">%3$s</span></a>';
            }else{
                $template = '<li><span id="car-%1$d" class="%2$s">%3$s</span></a>';
            }
            $string .= sprintf($template, $carid, $class,  $item['title']);
            if(is_array($this->maps[$carid])){
                $string .= '<ul>';
                foreach($this->maps[$carid] as $subid)
                    $string .= $this->recursiveTreeItem($subid);
                $string .= '</ul>'."\n";
            }
            $string .= '</li>'."\n";
        }
        return $string;
    }

}

